import React from 'react';
import { Form, Input, Button, Popover, Select, Row, Col, message, Checkbox } from 'antd';
import { postFn } from '@/api/commonApi';
import { FormComponentProps } from 'antd/lib/form'
interface FormProps extends FormComponentProps {
    goPath: any
}
const { Option } = Select;

class Register extends React.Component<any, any>{
    constructor(props: any) {
        super(props);
        this.state = {
            confirmDirty: false,
            count: 60,
            liked: true,
            userConfirm: {
                username: "",
                phone: ""
            }
        };

    }
    componentWillUnmount() {
        this.setState = (state, callback) => {
            return;
        };
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 18,
                    offset: 6,
                },
            },
        };
        // 手机号码选择
        const prefixSelector = getFieldDecorator('prefix', {
            initialValue: '86',
        })(
            <Select style={{ width: 70 }}>
                <Option value="86">+86</Option>
            </Select>,
        );
        // 用户名弹出
        const userNameContent = (
            <div>
                <span>· 用户名不允许有空格，允许中文</span> <br />
                <span>· 请勿包含隐私信息，一旦设置成功无法修改</span>
            </div>
        );
        // 密码弹出
        const passwordContent = (
            <div>
                <span>· 密码必须大于6位小于12位</span><br />
                <span>· 密码必须包含字母+数字</span>
            </div>
        )
        // 确认密码弹出
        const password2Content = (
            <div>
                <span>· 请再次输入您的密码</span>
            </div>
        )
        // 邮箱弹出
        const emailContent = (
            <div>
                <span>· 请输入您的邮箱号码 </span>
            </div>
        )
        // qq弹出
        const qqContent = (
            <div>
                <span>· 请输入您的qq号码 非必填</span>
            </div>
        )
        // 手机号弹出
        const phoneContent = (
            <div>
                <span>· 短信云没钱了，请确认手机号。不会发送短信，直接绑定手机</span><br />
                <span>· 短信云没钱了，请确认手机号。不会发送短信，直接绑定手机</span><br />
                <span>· 短信云没钱了，请确认手机号。不会发送短信，直接绑定手机</span>
            </div>
        )
        return (
            <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                <Popover content={userNameContent} trigger="focus" placement="right">
                    <Form.Item label="用户名">
                        {getFieldDecorator('username', {
                            rules: [
                                { required: true, message: '请设置用户名', whitespace: true },
                                {
                                    validator: this.validateToUsername,
                                }
                            ],
                        })(<Input placeholder="设置用户名" onBlur={this.userConfirmBlur.bind(this, 'username')} />)}
                    </Form.Item>
                </Popover>
                <Popover content={passwordContent} trigger="focus" placement="right">
                    <Form.Item label="登陆密码" hasFeedback>
                        {getFieldDecorator('password', {
                            rules: [
                                {
                                    required: true,
                                    message: '请设置密码',
                                },
                                {
                                    validator: this.validateToPassword,
                                },
                            ],
                        })(<Input.Password placeholder="请输入密码" />)}
                    </Form.Item>
                </Popover>
                <Popover content={password2Content} trigger="focus" placement="right">
                    <Form.Item label="确认密码" hasFeedback>
                        {getFieldDecorator('confirm', {
                            rules: [
                                {
                                    required: true,
                                    message: '请确认您的密码!',
                                },
                                {
                                    validator: this.compareToFirstPassword,
                                },
                            ],
                        })(<Input.Password placeholder="请再次输入密码" onBlur={this.handleConfirmBlur} />)}
                    </Form.Item>
                </Popover>
                <Popover content={phoneContent} trigger="focus" placement="right">
                    <Form.Item label="手机号码">
                        {getFieldDecorator('phone', {
                            rules: [{ required: true, message: '请输入您的手机号码!' }],
                        })(<Input addonBefore={prefixSelector} style={{ width: '100%' }} onBlur={this.userConfirmBlur.bind(this, 'phone')} />)}
                    </Form.Item>
                </Popover>
                <Popover content={qqContent} trigger="focus" placement="right">
                    <Form.Item label="QQ号码">
                        {getFieldDecorator('qq')(<Input placeholder="请输入qq" />)}
                    </Form.Item>
                </Popover>
                <Popover content={emailContent} trigger="focus" placement="right">
                    <Form.Item label="E-mail">
                        {getFieldDecorator('email', {
                            rules: [
                                {
                                    type: 'email',
                                    message: '输入的邮箱无效!',
                                },
                                {
                                    required: true,
                                    message: '请输入您的邮箱!',
                                },
                            ],
                        })(<Input placeholder="请输入邮箱号码" />)}
                    </Form.Item>
                </Popover>
                <Form.Item label="邮箱验证码">
                    <Row gutter={8}>
                        <Col span={14}>
                            {getFieldDecorator('captcha', {
                                rules: [{ required: true, message: '请输入验证码!' }],
                            })(<Input placeholder="请输入验证码" />)}
                        </Col>
                        <Col span={10}>
                            <Button style={{ width: "100%" }}
                                disabled={this.state.liked ? false : true}
                                onClick={this.getCaptcha.bind(this)}>
                                {this.state.liked ? '获取验证码' : `${this.state.count}秒后重新获取`}
                            </Button>
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item {...tailFormItemLayout}>
                    {getFieldDecorator('agreement', {
                        valuePropName: 'checked',
                        rules: [{ required: true, message: '还未勾选同意协议' }],
                    })(
                        <Checkbox>
                            <a href="#/about/fwtk" target="_blank">《泡豚服务条款》</a>
                        </Checkbox>,
                    )}
                </Form.Item>
                <Form.Item {...tailFormItemLayout}>
                    <Row gutter={8}>
                        <Col span={12}>
                            <Button type="primary" htmlType="submit">
                                同意协议并注册
                            </Button>
                        </Col>
                        <Col span={12}>
                            <div className="text-right">
                                <span>已有账号？ <a href="#/login/login">立即登录</a></span>
                            </div>
                        </Col>
                    </Row>
                </Form.Item>
            </Form>
        )
    }
    // 用户名验证
    validateToUsername = (rule: any, value: any, callback: any) => {
        let reg = new RegExp("[\u4E00-\u9FA5]+");
        if (!value || value.indexOf(" ") !== -1 || !!reg.test(value)) {
            callback('用户名不允许有空格且含有中文');
        } else {
            callback();
        }
    }
    // 确认账号是否已存在
    async userConfirmBlur(filed: string) {
        const { form } = this.props;
        let value = form.getFieldValue(filed);
        let param: any = {};
        param[filed] = value;
        let res: any = await postFn('userConfirm', param);
        if (!res) return;
        if (!res.isok) {
            let tempObj: any = {};
            if (filed === "username") {
                form.setFields({ username: { value: value, errors: [new Error('该用户名已被注册')] } });
                tempObj.username = value;
            } else {
                form.setFields({ phone: { value: value, errors: [new Error('该手机号码被注册')] } });
                tempObj.phone = value;
            }
            let userConfirm = Object.assign({}, this.state.userConfirm, tempObj);
            this.setState({ userConfirm: userConfirm });

        }
    }
    // 密码校验
    validateToPassword = (rule: any, value: any, callback: any) => {
        if (!value || value.length < 6) {
            callback('密码必须大于6位');
        } else {
            callback();
        }
    };

    // 确认密码
    handleConfirmBlur = (e: any) => {
        const { value } = e.target;
        this.setState({ confirmDirty: this.state.confirmDirty || !!value });
    };
    compareToFirstPassword = (rule: any, value: any, callback: any) => {
        const { form } = this.props;
        if (value && value !== form.getFieldValue('password')) {
            callback('您输入的两个密码不一致！');
        } else {
            callback();
        }
    };



    // 获取验证码倒计时
    async getCaptcha() {
        const { form } = this.props;
        let email = form.getFieldValue('email');
        if (!email || email === "") {
            message.error('还未填写邮箱');
            return;
        }
        this.countDown();
        let res: any = await postFn("getCaptcha", { email });
        if (!res) return;
        if (res.isok) {
            message.success(res.msg,5);
        } else {
            message.error(res.msg, 5);
            this.setState({ count: res.count + 1 });
        }
    };
    countDown() {
        const { count } = this.state;
        if (count === 1) {//当为0的时候，liked设置为true，button按钮显示内容为 获取验证码

            this.setState({
                count: 60,
                liked: true,
            })
        } else {
            this.setState({
                count: count - 1,
                liked: false,
            })
            setTimeout(() => this.countDown(), 1000)//每一秒调用一次
        }
    }

    // 提交
    handleSubmit = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form.validateFields(async (err: any, values: any) => {
            if (!values.agreement) {
                form.setFields({ agreement: { errors: [new Error('还未勾选同意协议')] } })
                return;
            }
            let tempObj = { ...this.state.userConfirm };
            let isBroken = true;
            for (const key in tempObj) {
                if (values[key] === tempObj[key]) {
                    if (key === "username") {
                        form.setFields({ username: { value: tempObj[key], errors: [new Error('该用户名已被注册')] } });
                    } else {
                        form.setFields({ phone: { value: tempObj[key], errors: [new Error('该手机号码被注册')] } });
                    }
                    isBroken = false;
                }
            }
            if (!isBroken) return;
            if (!err) {
                let res: any = await postFn("regUser", values);
                if (!res) return;
                if (res.isok) {
                    this.props.goPath("/login/login", { state: { username: values.username } })
                    message.success("注册成功，请牢记你的账号！");
                } else {
                    message.error(res.msg ? res.msg : "因网络延迟注册失败，请稍等1分钟重新注册！");
                }
            }
        });
    };
}

export default Form.create<FormProps>()(Register);